package com.itstudio.myforumsystem.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itstudio.myforumsystem.common.Result;
import com.itstudio.myforumsystem.entity.Article;
import com.itstudio.myforumsystem.entity.User;
import com.itstudio.myforumsystem.service.ArticleService;
import com.itstudio.myforumsystem.service.TypeService;
import com.itstudio.myforumsystem.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
@Slf4j
@RestController
@ResponseBody
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private TypeService typeService;
    @Autowired
    private ArticleService articleService;


    @PostMapping
    public Result save(@RequestBody Article article){

        if (article.getId()==null){
            article.setTime(DateUtil.now());
            User currentUser = TokenUtils.getCurrentUser();
            if (currentUser != null) {
                article.setUser(currentUser.getNickname());
            } else {
                // 处理用户未登录的情况，例如返回错误信息或跳过设置昵称
               log.warn("尝试保存文章时用户未登录");
            }

//            article.setUser(TokenUtils.getCurrentUser().getNickname());
            //TODO
            //需要加东西
            //设置浏览量
            article.setUserid(article.getUserid());
            article.setTypeid(article.getTypeid());
            article.setReadnumber(0);
        }
        try {
            articleService.saveOrUpdate(article);
            return Result.success();
        } catch (Exception e) {
            // 记录异常信息，返回错误结果
            log.error("保存文章时发生错误", e);
            return Result.error();
        }
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        articleService.removeById(id);
        return Result.success();
    }


    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids){
       articleService.removeByIds(ids);
       return Result.success();
    }

    @GetMapping
    public Result findAll(@RequestParam String start ,@RequestParam String end){
        QueryWrapper<Article> queryWrapper=new QueryWrapper<>();
        if (StrUtil.isBlank(start)){
            queryWrapper.eq("time",start);
        }
        if (StrUtil.isBlank(end)){
            queryWrapper.le("time",end);
        }
        List<Article> list = articleService.list(queryWrapper);
        return Result.success(list);
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        articleService.updateReadCount(id);
        Article article =  articleService.getById(id);
        String type = typeService.getById(article.getTypeid()).getName();
        article.setType(type);
        return Result.success(article);
    }

    @GetMapping("/page")
    public Result findPage(
            @RequestParam(required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false,defaultValue = "") String name//避免搜索为空时的报错
    ){
        // 检查 pageNum 是否为 null，如果是则设置默认值为 1
        pageNum = (pageNum != null) ? pageNum : 1;
        // 检查 pageSize 是否为 null，如果是则设置默认值为 10（或者你想设置的其他默认值）
        pageSize = (pageSize != null) ? pageSize : 3;
        IPage<Article> page=new Page<>(pageNum,pageSize);
        QueryWrapper<Article> queryWrapper=new QueryWrapper<>();
        if (StrUtil.isNotBlank(name)) {
            queryWrapper.like("name", name);
        }
        return Result.success(articleService.page(page,queryWrapper));

    }
    @GetMapping("/page/personalArticle")
    public Result findPersonalPage(
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize,
            @RequestParam(defaultValue = "") String name,
            @RequestParam(defaultValue = "") String user) {
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if(!"".equals(name)){
            queryWrapper.like("name",name);//框架是直接在中间加了一个and的
        }
        if(!"".equals(user)){
            queryWrapper.like("user",user);//框架是直接在中间加了一个and的
        }
        return Result.success(articleService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    @GetMapping("/personalPage")
    public Result findPersonalPage(
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize,
            @RequestParam Integer id)
    {
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        queryWrapper.eq("userid", id);
        return Result.success(articleService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    //通过用户名拿到文章信息
    @GetMapping("/pageOfUsersArticle")
    public Result findPersonalPage(@RequestParam(defaultValue = "")Integer id ){
        List<Article> articleList=articleService.findUsersArticle(id);
        return Result.success(articleList);

    }

    @GetMapping("/recommandArticle")
    public Result findInforOfRecommandArticle(){
        List<Article> articleList=articleService.selectRecommandArticleLimitFive();
        return Result.success(articleList);
    }
    //    通过用户id拿到收藏文章的信息
    @GetMapping("/selectCollectionArticle/{userid}")
    public Result findCollectionArticle(@PathVariable Integer userid){
        List<Article> articleList=articleService.selectCollectionArticle(userid);
        return Result.success(articleList);
    }



}
